﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using Izhgtu.SandcastlePackage;
using Microsoft.Build.BuildEngine;
using Microsoft.VisualStudio;
//using Microsoft.VisualStudio.Package;
using Microsoft.VisualStudio.Project.Automation;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.Xml.Linq;

namespace Students.Sandcastle.PropertyEditor
{



    public partial class PlugInConfigurations : Form
    {
        public int numberPlagin = 0;
        public PlugInConfigurations()
        {
            InitializeComponent();

            AddPlugin();

            CurrentLoadPlugin();
        }

        /// <summary>
        /// Динамическое добавление плагинов SHFB 
        /// </summary>
        private void AddPlugin() 
        {
            //Пока добавляем в ручную
            Plugin additionContentOnly = new Plugin("Additional Content Only", 
                                                    new Version("1.8.0.3"), 
                                                    "Copyright © 2007-2010, Eric Woodruff, All Rights Reserved", 
                                                    "This plug-in can be used to build a help file consisting of nothing but conceptual content and/or additional content items.  It is also useful for proofreading your conceptual and/or additional content without having to build all the API topics.");

            listPlugin.Items.Add(additionContentOnly);
        }


        /// <summary>
        /// Ищем в списке доступных плагинов
        /// </summary>
        /// <param name="idName">Имя плагина</param>
        /// <returns></returns>
        private Plugin SearchToNameListPlagin(string idName)
        {
            foreach(Plugin plug in listPlugin.Items)
            {
                if (plug.namePlugin == idName)
                    return plug;
            }
            return null;
        }

        /// <summary>
        /// Ищем в списке используемых плагинов
        /// </summary>
        /// <param name="idName">Имя плагина</param>
        /// <returns></returns>
        private Plugin SearchToNameCurrentPlagin(string idName)
        {
            foreach (Plugin plug in currentPlagin.Items)
            {
                if (plug.namePlugin == idName)
                    return plug;
            }
            return null;
        }

        /// <summary>
        /// Загружаем данные с файла настроек
        /// </summary>
        public void CurrentLoadPlugin()
        {
            EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
            EnvDTE.Project prj = dte.Solution.Projects.Item(1);

            String pathToProjectFile = prj.FullName;

            XDocument doc = XDocument.Load(pathToProjectFile);
            foreach (XElement elem in doc.Root.Elements())
            {
                foreach (XElement el in elem.Elements())
                {

                    if (el.Name.LocalName == "PlugInConfigurations")
                    {
                        numberPlagin = 0;
                        foreach (XElement element in el.Elements())
                        {
                            String idName = element.Attribute("id").Value;
                            Plugin curPlag = SearchToNameListPlagin(idName);
                            if (curPlag != null)
                            {
                                numberPlagin++;
                                currentPlagin.Items.Add(curPlag);
                            }
                        }

                        continue;
                    }
                }
            
            
            }

 
        }

        private void PlugInConfigurations_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Добавляем плагин в список используемые плагинов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            Plugin selected = (Plugin)listPlugin.SelectedItem;
            if (selected != null)
            {
                Plugin search = SearchToNameCurrentPlagin(selected.namePlugin);
                if (search == null)
                {
                    currentPlagin.Items.Add(selected);
                }
                else 
                {
                    MessageBox.Show("Такой плагин уже существует");
                }
            }
            else
            {
                MessageBox.Show("Выберите плагин");
            }
            
        }


        /// <summary>
        /// Удаляем плагин из списка используемых плагинов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            var selected = currentPlagin.SelectedItem;
            if (selected != null)
            {
                //int index = currentPlagin.SelectedIndices;
                currentPlagin.Items.Remove(selected);
            }
            else
            {
                MessageBox.Show("Выберите плагин");
            }
        }

        //Сохраняем настройку в файл
        private void SaveProperties()
        {
            EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
            EnvDTE.Project prj = dte.Solution.Projects.Item(1);

            //Пока не работают настройка делаем заглушку
            String configuration = "<configuration />";
            String enabled =  bool.TrueString;

            String result = " ";

            numberPlagin = 0;
            foreach (Plugin item in currentPlagin.Items)
	            {
                     String property = String.Format("<PlugInConfig id=\"{0}\" enabled=\"{1}\" xmlns=\"\">{2}</PlugInConfig>", item.namePlugin, enabled, configuration);
                     result += property;
                     numberPlagin++;
	            }
            
            
            Izhgtu.SandcastlePackage.SandcastleProjectNode node = (SandcastleProjectNode)((OASandcastleProject)((OAVSProject)prj.Object).Project).typeProject;
            node.SetProjectProperty("PlugInConfigurations", result);
            
            prj.Save("");
        }


        protected override void OnClosed(EventArgs e)
        {
            SaveProperties();
            base.OnClosed(e);
        }
    }
}
